// Copyright 2024 Zenoh P2P Project
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

use serde::{Deserialize, Serialize};
use libp2p::StreamProtocol;

/// Handshake protocol name
pub const PROTOCOL_NAME: StreamProtocol = StreamProtocol::new("/zenop2p/handshake/1.0.0");

/// Handshake request message
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct HandshakeRequest {
    /// Peer ID of the requesting node
    pub peer_id: String,
    /// Cryptographic credential signed by root private key
    pub credential: Vec<u8>,
    /// Timestamp to prevent replay attacks
    pub timestamp: u64,
    /// Nonce for additional security
    pub nonce: Vec<u8>,
}

/// Handshake response message
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct HandshakeResponse {
    /// Whether the handshake was successful
    pub is_valid: bool,
    /// Descriptive message about the result
    pub message: String,
    /// Error details if handshake failed
    pub error: Option<HandshakeError>,
    /// Server timestamp for synchronization
    pub server_timestamp: u64,
}

/// Handshake error types
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub enum HandshakeError {
    /// Invalid cryptographic credential
    InvalidCredential,
    /// Invalid peer ID format
    InvalidPeerId,
    /// Internal server error
    InternalError,
    /// Unauthorized access
    Unauthorized,
    /// Timestamp validation failed
    InvalidTimestamp,
    /// Nonce validation failed
    InvalidNonce,
}

impl std::fmt::Display for HandshakeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HandshakeError::InvalidCredential => write!(f, "Invalid credential"),
            HandshakeError::InvalidPeerId => write!(f, "Invalid peer ID"),
            HandshakeError::InternalError => write!(f, "Internal error"),
            HandshakeError::Unauthorized => write!(f, "Unauthorized"),
            HandshakeError::InvalidTimestamp => write!(f, "Invalid timestamp"),
            HandshakeError::InvalidNonce => write!(f, "Invalid nonce"),
        }
    }
}

impl std::error::Error for HandshakeError {}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_protocol_name() {
        assert_eq!(PROTOCOL_NAME.to_string(), "/zenop2p/handshake/1.0.0");
    }

    #[test]
    fn test_handshake_request_serialization() {
        let request = HandshakeRequest {
            peer_id: "test_peer".to_string(),
            credential: vec![1, 2, 3, 4],
            timestamp: 1234567890,
            nonce: vec![5, 6, 7, 8],
        };

        let serialized = serde_json::to_string(&request).unwrap();
        let deserialized: HandshakeRequest = serde_json::from_str(&serialized).unwrap();

        assert_eq!(request.peer_id, deserialized.peer_id);
        assert_eq!(request.credential, deserialized.credential);
        assert_eq!(request.timestamp, deserialized.timestamp);
        assert_eq!(request.nonce, deserialized.nonce);
    }

    #[test]
    fn test_handshake_response_serialization() {
        let response = HandshakeResponse {
            is_valid: true,
            message: "Authentication successful".to_string(),
            error: None,
            server_timestamp: 1234567890,
        };

        let serialized = serde_json::to_string(&response).unwrap();
        let deserialized: HandshakeResponse = serde_json::from_str(&serialized).unwrap();

        assert_eq!(response.is_valid, deserialized.is_valid);
        assert_eq!(response.message, deserialized.message);
        assert_eq!(response.error, deserialized.error);
        assert_eq!(response.server_timestamp, deserialized.server_timestamp);
    }
}